package Read;

import Service.UniversityService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.example.University;
import util.Condition;
import util.JSONUtil;
import util.Pagination;
import util.UniversityControllerHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

@WebServlet("/UniversityRead.ctl")
public class UniversityReadCtl extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");//创建JSON对象message，以便往前端响应信息
        JSONObject message_jsonObj = new JSONObject();
        String req_jsonStr = JSONUtil.getJSON(request);
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr, JSONObject.class);
        if (req_jsonObj == null) {
            message_jsonObj.put("message", "未收到请求信息");
            response.getWriter().println(message_jsonObj);
            return;
        }
        try {
            Pagination pagination = UniversityControllerHelper.getPagination(req_jsonObj);
            List<Condition> conditionList = UniversityControllerHelper.getCondition(req_jsonObj);
            Collection<University> universitys = UniversityService.getInstance().findAll(conditionList,pagination);
            message_jsonObj.put("totalNum",pagination.getTotalNum());
            message_jsonObj.put("records",universitys);
            response.getWriter().println(message_jsonObj);
        } catch (SQLException e) {
            message_jsonObj.put("message", "数据库操作异常");
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        } catch (Exception e) {
            message_jsonObj.put("message", "网络异常");
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        }
    }
}
